import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.*;

public class Test {

    public static void main(String[] args) throws Exception {
        Counter counter = new Counter();
        Thread t1 = new Thread(() -> {
            try {
                for (int i = 0; i < 10000; i++) {
                    counter.add(1);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        t1.start();
        t1.join();

        System.out.println("Final count: " + counter.count);
    }

}

class Counter {
    private final ReentrantLock lock = new ReentrantLock();
    int count;

    public void add(int n) throws InterruptedException {
        // lock.lock();
        lock.tryLock(1, TimeUnit.SECONDS);
        // 述代码在尝试获取锁的时候，最多等待1秒。如果1秒后仍未获取到锁，tryLock()返回false，程序就可以做一些额外处理，而不是无限等待下去
        try {
            count += n;
        } finally {
            lock.unlock();
        }
    }
}